'use strict'
const whiteList = require('../lib/whiteList')
const minioClient = require('../lib/minIO')
const config = require('../config')
const fs = require('fs')
// const fileManagerServices = require('../services').fileManagerService

const fileManagerController = {}

// 上传文件
fileManagerController.uploadFile = async (ctx, next) => {
    whiteList.needAdmin(ctx, next)
    // console.log('fileManagerController', ctx.request.files.upload)
    // ctx.result = await articleServices.createArticle(articleList)

    let file = ctx.request.files.upload
    // console.log(file);
    let suffix = file.name.split('.').pop()
    if(suffix==='blob'||suffix===''){
        suffix = 'jpeg'
    }
    console.log(file);
    console.log(suffix);
    let fileName = guid() + '.' + suffix
    const reader = fs.createReadStream(file.path)
    let result = await new Promise((resolve, reject) => {
        return minioClient.putObject('blog-img', fileName, reader, file.size, function (err, etag) {
            console.log('putObject', err, etag)
            if (err) {
                reject(err)
            } else {
                resolve(config.staticResBaseUrl + fileName)
            }
        })
    })

    console.log('result', result)
    ctx.result = result

    return next()
}

// 删除文章
fileManagerController.removeFile = async (ctx, next) => {
    whiteList.needAdmin(ctx, next)
    // ctx.result = await articleServices.deleteArticle(articleList)
    ctx.result = {}
    return next()
}


function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

module.exports = fileManagerController
